package tech.bmatch.image.service.Impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tech.bmatch.image.model.Photo;
import tech.bmatch.image.model.User;
import tech.bmatch.image.service.UserService;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @program:StorePicture
 * @author:LinJinhao
 * @create:2018-11-02 09:46
 **/
public class UserStoreServiceImpl implements UserService {
    private Map<String, User> users;
    private static ObjectMapper objectMapper = new ObjectMapper();
    private static File file = new File("./user.json");
    private static final Logger logger = LoggerFactory.getLogger(UserStoreServiceImpl.class);
    public static final float maxSpace = 2097152f;

    //上传数据
    @Override
    public void init() {

        if (!file.exists()) {
            return;
        }
        try {
            List<User> userList = objectMapper.readValue(file, new TypeReference<List<User>>() {
            });
            for (User user : userList) {
                uploadUser(user);
            }
        } catch (IOException e) {
            logger.error("", e);
        }
    }
    //上传数据
    @Override
    public void uploadUser(User user) {
        if (users == null) {
            users = new HashMap<String, User>();
        }
        if (user == null) {
            return;
        }

        users.put(user.getUserId(), user);

        List<User> userList = users.values().stream().collect(Collectors.toList());

        store(userList);
    }


    /** 将数据写入
     * @Param:users 用户
     * @return:
     **/
    public void store(List<User> users) {
        if (users == null) {
            return;
        }
        try {
            objectMapper.writeValue(file, users);
        } catch (IOException e) {
            logger.error("", e);
        }

    }
    /*
     * @param 创建子文件夹
     * @param 路径:在某一时间不同用户所上传的图片
     * */
    @Override
    public Photo upload(String userId,byte[] files, String name,String userName) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String time = sdf.format(System.currentTimeMillis());

        String applyPath = storePath+"/"+time+"/"+userName+"/"+name;
        String type = name.substring(name.lastIndexOf(".") + 1);

        File storeFile = new File(applyPath);
        storeFile.getParentFile().mkdirs();

        File f = new File(storePath+"/2018-11-03/"+userName);
        float overSpace = maxSpace - getDirSpace(f)-storeFile.length();


        //将图片存储到默认路径的文件夹中，完成图片存储
        if (overSpace > 0) {
            FileOutputStream out = null;
            try {

                out = new FileOutputStream(storeFile);
                out.write(files);
                out.close();

            } catch (Exception e) {
                e.printStackTrace();
            }
            BufferedImage image = null;
            try {
                image = ImageIO.read(new FileInputStream(storeFile));
            } catch (IOException e) {
                e.printStackTrace();
            }

            Photo photo = new Photo();
            int height = image.getHeight();
            int width = image.getWidth();
            float size = storeFile.length();

            Date uploadDate = new Date();

            photo.setHeight(height);
            photo.setWidth(width);
            photo.setName(name);
            photo.setSize(size);
            photo.setStorePath(storePath);
            photo.setType(type);
            photo.setUploadDate(uploadDate);
            photo.setUserId(userId);
            logger.info("上传完毕！回车继续操作其他指令");
            System.out.println(userName+"用户的剩余空间容量:"+overSpace/1024+"KB");
        }else {
            logger.error(userName+"用户的空间容量不足!");
        }

        return null;
    }
    /** 计算文件大小
    * @Param: file 文件路径
    * @return: float
    **/
    public static float getDirSpace(File file) {
        //判断文件是否存在
            if (file.exists()) {
                //如果是目录则递归计算其内容的总大小
                if (file.isDirectory()) {
                    File[] f1 = file.listFiles();
                    float userSpace = 0;
                    for (File f : f1)
                        userSpace += getDirSpace(f);
                    return userSpace;
                } else {
                    //如果是文件则直接返回其大小,以B为单位
                    float userSpace = (float) file.length();
                    return userSpace;
                }
            } else {
            System.out.println("文件或者文件夹不存在，请检查路径是否正确！");
            return 0;
            }
        }





    /**浏览特定用户的所有图片
    * @Param; userName 用户名
    * @return:
    **/
    public void browse(String userName) {
        String path = storePath+"/2018-11-03/"+userName;
        File file = new File(path);
        if (file.exists()) {
            File[] files = file.listFiles();
            if (files.length == 0) {
                System.out.println("文件夹是空的!");
                return;
            } else {
                for (File file2 : files) {
                    if (file2.isDirectory()) {
                        System.out.println("文件夹:" + file2.getAbsolutePath());
                    } else {
                        System.out.println("图片:" + file2.getName());
                    }
                }
            }
        } else {
            System.out.println("文件不存在!");
        }
    }


    /** 打水印
    * @Param: name 图片名字
    * @return:
    **/
    public void markImageByIcon(String name,int x,int y){
        String imagePath = storePath+"/2018-11-03/ff/"+name;
        OutputStream out = null;
        try {
            //读取图片
            Image image = ImageIO.read(new File(imagePath));
            BufferedImage bufferedImage = new BufferedImage(image.getWidth(null),
                    image.getHeight(null), BufferedImage.TYPE_INT_RGB);

            //创建画笔对象
            Graphics2D g = bufferedImage.createGraphics();

            //设置对线段的锯齿边缘的处理
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);

            g.drawImage(image.getScaledInstance(image.getWidth(null), image.getHeight(null)
                    , image.SCALE_SMOOTH), 0, 0, null);
            //创建水印
            String iconPath = "/Users/linjinhao/Downloads/logo/logo.jpg";
            ImageIcon imageIcon = new ImageIcon(iconPath);
            Image icon = imageIcon.getImage();

            //水印透明度
            float transparency = 1f;

            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
                    transparency));

            //设置水印大小
            int iconWidth = imageIcon.getIconWidth();
            int iconHeight = imageIcon.getIconHeight();

            //设置水印位置
            g.drawImage(icon, x, y, iconWidth, iconHeight, null);

            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));

            g.dispose();

            out = new FileOutputStream(imagePath);

            ImageIO.write(bufferedImage, "JPG", out);

            System.out.println("添加水印完成");
        } catch (IOException e) {
            logger.error("",e);
        }finally {
            try {
                if (null != out) {
                    out.close();
                }
            } catch (IOException e) {
                logger.error("", e);
            }
        }
    }
}
